package utils;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import database.Class;
import database.ClassDb;
import database.User;
import database.UserDb;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;

/**
 * Created by jimmyhsu on 2016/12/7.
 */
public class ExportExcelUtil {
    /**
     *
     * @param response
     *   请求
     * @param fileName
     *   文件名 如："学生表"
     * @param bigTitle
     *   Excel的第一行标题
     * @param excelHeader
     *   excel表头数组，存放"姓名#name"格式字符串，"姓名"为excel标题行， "name"为对象字段名
     * @param dataList
     *   数据集合，需与表头数组中的字段名一致，并且符合javabean规范
     * @return 返回一个HSSFWorkbook
     * @throws Exception
     */
    public static <T> HSSFWorkbook export(HttpServletResponse response, String fileName,
                                          String bigTitle, String[] excelHeader,
                                          Collection<T> dataList) throws Exception {
        // 设置请求
        response.setContentType("application/application/vnd.ms-excel");
        response.setHeader("Content-disposition",
                "attachment;filename=" + URLEncoder.encode(fileName + ".xls", "UTF-8"));
        // 创建一个Workbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 设置标题样式
        HSSFCellStyle titleStyle = wb.createCellStyle();
        // 设置单元格边框样式
        titleStyle.setBorderTop(BorderStyle.THIN);// 上边框 细边线
        titleStyle.setBorderBottom(BorderStyle.THIN);// 下边框 细边线
        titleStyle.setBorderLeft(BorderStyle.THIN);// 左边框 细边线
        titleStyle.setBorderRight(BorderStyle.THIN);// 右边框 细边线
        // 设置单元格对齐方式
        titleStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
        // 设置字体样式
        Font titleFont = wb.createFont();
//        titleFont.setFontHeightInPoints((short) 15); // 字体高度
        titleFont.setFontName("黑体"); // 字体样式
        titleStyle.setFont(titleFont);
        // 在Workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(fileName);
        // 标题数组
        String[] titleArray = new String[excelHeader.length];
        // 字段名数组
        String[] fieldArray = new String[excelHeader.length];
        for (int i = 0; i < excelHeader.length; i++) {
            String[] tempArray = excelHeader[i].split("#");// 临时数组 分割#
            titleArray[i] = tempArray[0];
            fieldArray[i] = tempArray[1];
        }
        // 在sheet中添加标题行
        HSSFRow bigTitleRow = sheet.createRow(0);// 行数从0开始
        HSSFCell bigTitleCell = bigTitleRow.createCell(0);
        bigTitleCell.setCellValue(bigTitle);
        bigTitleCell.setCellStyle(titleStyle);
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, titleArray.length));
        sheet.autoSizeColumn(0, true);

        HSSFRow row = sheet.createRow(1);
        HSSFCell sequenceCell = row.createCell(0);// cell列 从0开始 第一列添加序号
        sequenceCell.setCellValue("序号");
        sequenceCell.setCellStyle(titleStyle);
        sheet.autoSizeColumn(0);// 自动设置宽度
        // 为标题行赋值
        for (int i = 0; i < titleArray.length; i++) {
            HSSFCell titleCell = row.createCell(i + 1);// 0号位被序号占用，所以需+1
            titleCell.setCellValue(titleArray[i]);
            titleCell.setCellStyle(titleStyle);
            sheet.autoSizeColumn(i + 1);// 0号位被序号占用，所以需+1
        }
        // 数据样式 因为标题和数据样式不同 需要分开设置 不然会覆盖
        HSSFCellStyle dataStyle = wb.createCellStyle();
        // 设置数据边框
        dataStyle.setBorderTop(BorderStyle.THIN);// 上边框 细边线
        dataStyle.setBorderBottom(BorderStyle.THIN);// 下边框 细边线
        dataStyle.setBorderLeft(BorderStyle.THIN);// 左边框 细边线
        dataStyle.setBorderRight(BorderStyle.THIN);// 右边框 细边线
        // 设置居中样式
        dataStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        dataStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
        // 设置数据字体
        Font dataFont = wb.createFont();
        dataFont.setFontHeightInPoints((short) 12); // 字体高度
        dataFont.setFontName("宋体"); // 字体
        dataStyle.setFont(dataFont);
        // 遍历集合数据，产生数据行
        Iterator<T> it = dataList.iterator();
        int index = 0;
        while (it.hasNext()) {
            index++;// 0号位被占用 所以+1
            row = sheet.createRow(index + 1);
            // 为序号赋值
            HSSFCell sequenceCellValue = row.createCell(0);// 序号值永远是第0列
            sequenceCellValue.setCellValue(index);
            sequenceCellValue.setCellStyle(dataStyle);
            sheet.autoSizeColumn(0);
            T t = it.next();
            // 利用反射，根据传过来的字段名数组，动态调用对应的getXxx()方法得到属性值
            for (int i = 0; i < fieldArray.length; i++) {
                HSSFCell dataCell = row.createCell(i + 1);
                dataCell.setCellStyle(dataStyle);
                sheet.autoSizeColumn(i + 1);
                String fieldName = fieldArray[i];
                String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);// 取得对应getXxx()方法
                java.lang.Class<? extends Object> tCls = t.getClass();// 泛型为Object以及所有Object的子类
                Method getMethod = tCls.getMethod(getMethodName);// 通过方法名得到对应的方法
                Object value = getMethod.invoke(t);// 动态调用方,得到属性值
                if (value != null) {
                    dataCell.setCellValue(value.toString());// 为当前列赋值
                }
            }
        }

        OutputStream outputStream = response.getOutputStream();// 打开流
        wb.write(outputStream);// HSSFWorkbook写入流
        wb.close();// HSSFWorkbook关闭
        outputStream.flush();// 刷新流
        outputStream.close();// 关闭流
        return wb;
    }

    public static boolean importStudent(InputStream is) {
        List<User> usersToInsert = new ArrayList<User>();

        try {
            HSSFWorkbook workbook = new HSSFWorkbook(is);
//            for (int i = 0; i < workbook.getNumberOfSheets(); i++){
            //应该只有一张表
            HSSFSheet sheet = workbook.getSheetAt(0);
            for (int j = 1; j <= sheet.getLastRowNum(); j++) {
                HSSFRow row = sheet.getRow(j);
                HSSFCell cell_id = row.getCell(0);
                System.out.println(cell_id.getNumericCellValue());
                String studentId = new BigDecimal(cell_id.getNumericCellValue()).toString();
                if (!studentId.matches("[0-9]*")) {
                    throw new Exception("wrong id: " + studentId);
                }
                String name = row.getCell(1).getStringCellValue();
                String sex = row.getCell(2).getStringCellValue();
                if (!sex.equals("男") && !sex.equals("女")) {
                    throw new Exception("wrong sex: " + sex);
                }

                String institute = row.getCell(3).getStringCellValue();
                String grade = row.getCell(4).getStringCellValue();
                String dormitory = row.getCell(5).getStringCellValue();
                String tel = new BigDecimal(row.getCell(6).getNumericCellValue()).toString();
                if (!tel.matches("[0-9]{11}")) {
                    throw new Exception("wrong tel: " + tel);
                }
                String email = row.getCell(7).getStringCellValue();
                String password = row.getCell(8).getStringCellValue();
                String userInClass = row.getCell(9).getStringCellValue();
                String branch = row.getCell(10).getStringCellValue();
                User user = new User(studentId, name, sex, institute, branch, grade, "", dormitory,
                        "user", tel, email, System.currentTimeMillis() + "", password, userInClass, 0);
                usersToInsert.add(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                is.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        for (User user : usersToInsert) {
            if (UserDb.userNotExists(user.getId())) {
                UserDb.insertStudent(user.getId(), user.getName(), user.getSex(), user.getInstitute(),
                        user.getDormitory(), user.getTel(), user.getBranch(), user.getGrade(), user.getEmail(),
                        user.getType());
            } else {
                UserDb.updateStudent(user.getId(), user.getName(), user.getSex(), user.getInstitute(),
                        user.getDormitory(), user.getTel(), user.getBranch(), user.getGrade(), user.getEmail(),
                        user.getType());
            }
            if (!StringUtils.isEmpty(user.getUserInClass())) {
                String className = user.getUserInClass();
                Class aClass = ClassDb.selectClassByName(className);
                if (aClass == null) {
                    ClassDb.insertClass(className);
                    aClass = ClassDb.selectClassByName(className);
                }
                if (ClassDb.isUserInOtherClass(user.getId(), aClass.getId())) {
                    ClassDb.updateUserInClass(user.getId(), aClass.getId());
                }
                ClassDb.insertUserInClass(user.getId(), aClass.getId(), 0);
            }
        }
        return true;
    }
}
